package com.chenxinzhimusic.ui.page

import android.annotation.SuppressLint
import android.os.Build
import androidx.activity.compose.BackHandler
import androidx.annotation.RequiresApi
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandHorizontally
import androidx.compose.animation.shrinkHorizontally
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBackIosNew
import androidx.compose.material.icons.filled.PlayCircleOutline
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.chenxinzhimusic.api.Api
import com.chenxinzhimusic.entity.PlayList
import com.chenxinzhimusic.entity.SearchList
import com.chenxinzhimusic.entity.SuggestionItem
import com.chenxinzhimusic.entity.addMusic
import com.chenxinzhimusic.entity.toMusicInfo
import com.chenxinzhimusic.refreshFlow
import com.chenxinzhimusic.viewmodel.MusicSearchViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
import org.koin.compose.viewmodel.koinViewModel

@SuppressLint("ConfigurationScreenWidthHeight")
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
@Composable
fun MusicSearchScreen(
    viewModel: MusicSearchViewModel = koinViewModel(),
    sharedFlow: MutableSharedFlow<Unit>,
) {
    val focusManager = LocalFocusManager.current
    var showTip by rememberSaveable { mutableStateOf(false) }
    LaunchedEffect(viewModel.searchContent) {
        launch(Dispatchers.IO) {
            if (viewModel.searchContent.isBlank()) {
                viewModel.searchTipList = listOf()
                return@launch
            }
            val search = Api.search(viewModel.searchContent)
            viewModel.searchTipList = (search.data ?: listOf()).map { str ->
                SuggestionItem(
                    try {
                        str.substring(8, str.indexOf("SNUM"))
                    } catch (_: Exception) {
                        ""
                    }
                )
            }.take(8)
        }
    }
    val rememberCoroutineScope = rememberCoroutineScope()
    val content = LocalContext.current
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(bottom = 8.dp)
    ) {
        Box {
            GradientSearchBar(
                viewModel.searchContent,
                {
                    viewModel.searchContent = it
                },
                modifier = Modifier.padding(horizontal = if (LocalConfiguration.current.screenWidthDp < 360) 12.dp else 20.dp),
                "请输入歌曲名",
                {
                    showTip = false
                    focusManager.clearFocus()
                    rememberCoroutineScope.launch {
                        viewModel.searchContentAction = viewModel.searchContent
                    }
                }, {
                    showTip = it
                }, showTip, backHandler = {
                    focusManager.clearFocus()
                })
        }
        val rememberLazyListState = rememberLazyListState()
        AnimatedContent(

            showTip,
            transitionSpec = {
                slideInHorizontally(
                    initialOffsetX = { -it },
                    animationSpec = tween(500)
                ) togetherWith slideOutHorizontally(
                    targetOffsetX = { -it }, // 向上退出
                    animationSpec = tween(500)
                )
            },
            modifier = Modifier
                .fillMaxSize(),
        ) {

            val absList = viewModel.searchList.collectAsLazyPagingItems()
            if (it) {
                SearchSuggestionList(
                    viewModel, {
                        showTip = false
                        focusManager.clearFocus()
                    }
                )

            } else {

                LazyColumn(
                    state = rememberLazyListState,
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(
                        start = 8.dp,
                        end = 8.dp,
                        top = 4.dp,
                        bottom = if (LocalConfiguration.current.screenHeightDp < 600) 8.dp else 12.dp
                    )
                ) {
                    if (absList.itemCount > 0) {
                        item {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(
                                        horizontal = if (LocalConfiguration.current.screenWidthDp < 360) 8.dp else 16.dp,
                                        vertical = 8.dp
                                    )
                                    .clip(RoundedCornerShape(8.dp))
                                    .background(Color(0xB42D2D2D))
                                    .clickable {
                                        // 播放全部逻辑
                                        rememberCoroutineScope.launch(Dispatchers.IO) {
                                            if (absList.itemCount > 0) {
                                                sharedFlow.emit(Unit)
                                                var page: SearchList? = null
                                                var count = 0
                                                while (page == null && count++ < 100) {
                                                    page = Api.page(
                                                        viewModel.searchContent,
                                                        rn = Int.MAX_VALUE
                                                    )
                                                    delay(1)
                                                }
                                                page?.abslist?.map { it.toMusicInfo() }?.let {
                                                    it.firstOrNull()?.let { info ->
                                                        content.addMusic(
                                                            info,
                                                            PlayList(musicList = it.toMutableList())
                                                        )
                                                    }
                                                }
                                                refreshFlow.tryEmit(Unit)

                                            }
                                        }
                                    }
                                    .padding(vertical = 10.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    imageVector = Icons.Default.PlayCircleOutline,
                                    contentDescription = "播放全部",
                                    tint = Color.White,
                                    modifier = Modifier
                                        .padding(start = if (LocalConfiguration.current.screenWidthDp < 360) 12.dp else 16.dp)
                                        .size(if (LocalConfiguration.current.screenWidthDp < 360) 20.dp else 24.dp)
                                )
                                Text(
                                    text = "播放全部",
                                    color = Color.White,
                                    style = MaterialTheme.typography.titleMedium,
                                    modifier = Modifier.padding(start = 12.dp, end = 4.dp)
                                )
                                Box(modifier = Modifier.weight(1f)) { /* 弹性空间 */ }

                            }
                            Spacer(modifier = Modifier.height(8.dp))
                        }
                    }
                    items(absList.itemCount, key = absList.itemKey {
                        """${it.mUSICRID}:${it.dCTARGETID}:${it.aRTISTID}:${it.aLBUMID}"""
                    }) { index ->
                        MusicItemView(absList[index]!!, sharedFlow, index, rememberLazyListState)
                    }
                    absList.apply {
                        when {
                            loadState.refresh is LoadState.Loading -> {
                                item {
                                    Box(
                                        modifier = Modifier.fillParentMaxSize(),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        CircularProgressIndicator()
                                    }
                                }
                            }

                            loadState.append is LoadState.Loading -> {

                                item {
                                    Box(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(16.dp),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        CircularProgressIndicator()
                                    }
                                }
                            }

                            loadState.append.endOfPaginationReached
                                -> {
                                item {
                                }
                            }

                            loadState.refresh is LoadState.Error || loadState.append is LoadState.Error -> {
                                val error = (loadState.refresh as? LoadState.Error)?.error
                                    ?: (loadState.append as? LoadState.Error)?.error
                                item {
                                    Box(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(16.dp),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        Text(
                                            text = "加载失败: ${error?.localizedMessage ?: "未知错误"}，点击重试",
                                            color = Color.Red,
                                            modifier = Modifier.clickable {
                                                retry()
                                            }
                                        )
                                        // 可以添加一个重试按钮
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

    }
}

@Composable
fun GradientSearchBar(
    value: String,
    onValueChange: (String) -> Unit,
    modifier: Modifier = Modifier,
    placeholder: String = "搜索",
    onSearch: () -> Unit = {},
    forceHandler: (Boolean) -> Unit,
    showBack: Boolean,
    backHandler: () -> Unit = {}
) {
    BackHandler(showBack) {
        backHandler()
    }
    Row(verticalAlignment = Alignment.CenterVertically) {
        AnimatedVisibility(
            showBack, enter = expandHorizontally(
                animationSpec = tween(durationMillis = 300)
            ),
            exit = shrinkHorizontally(
                animationSpec = tween(durationMillis = 300)
            )
        ) {
            Icon(
                imageVector = Icons.Default.ArrowBackIosNew,
                contentDescription = "返回",
                tint = Color.Gray,
                modifier = Modifier
                    .padding(start = 4.dp, end = 6.dp)
                    .size(25.dp)
                    .pointerInput(Unit) {
                        detectTapGestures {
                            backHandler()
                        }
                    }
            )
        }
        Box(
            modifier = modifier

                .fillMaxWidth()
                .animateContentSize()
                .height(48.dp)
                .background(
                    brush = Brush.horizontalGradient(
                        colors = listOf(
                            Color(0xB41F1F1F),
                            Color(0xB42D2D2D),
                            Color(0xB43A2D3E) // 渐变尾色，可调整
                        )
                    ),
                    shape = RoundedCornerShape(12.dp)
                )
                .padding(horizontal = 12.dp, vertical = 6.dp)
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.fillMaxSize()
            ) {
                Icon(
                    imageVector = Icons.Default.Search,
                    contentDescription = "搜索",
                    tint = Color.Gray,
                    modifier = Modifier.padding(end = 8.dp)
                )

                Box(modifier = Modifier.weight(1f)) {
                    BasicTextField(
                        value = value,
                        cursorBrush = SolidColor(Color.White),
                        onValueChange = onValueChange,
                        singleLine = true,
                        textStyle = LocalTextStyle.current.copy(color = Color.White),
                        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
                        keyboardActions = KeyboardActions(onSearch = { onSearch() }),
                        modifier = Modifier
                            .fillMaxWidth()
                            .onFocusChanged {
                                forceHandler(it.isFocused)
                            }
                    )

                    // Placeholder
                    if (value.isEmpty()) {
                        Text(
                            text = placeholder,
                            color = Color.Gray
                        )
                    }
                }
            }
        }
    }
}

